﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace COMMON.Http.Sender
{
    /// <summary>
    /// post请求发送器
    /// </summary>
    public class PostSender
    {
        /// <summary>
        /// 请求地址
        /// </summary>
        public string url { get; set; }
        /// <summary>
        /// 请求参数
        /// </summary>
        public IDictionary<string, object> paras { get; set; }

        /// <summary>
        /// header信息
        /// </summary>
        public IDictionary<string, object> header { get; set; }
        /// <summary>
        /// 真正的header信息
        /// </summary>
        public WebHeaderCollection Headers;


        /// <summary>
        /// 默认构造器
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="paras">请求参数</param>
        public PostSender(string url, IDictionary<string, object> paras)
        {
            this.url = url;
            this.paras = paras;
        }
        /// <summary>
        /// 全参构造
        /// </summary>
        /// <param name="url"></param>
        /// <param name="paras"></param>
        /// <param name="header"></param>
        public PostSender(string url, IDictionary<string, object> paras, IDictionary<string, Object> header)
        {
            this.url = url;
            this.paras = paras;
            this.header = header;
        }


        /// <summary>  
        /// 创建POST方式的HTTP请求  
        /// </summary>  
        public HttpWebResponse send(int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            //如果是发送HTTPS请求  
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";

            //设置代理UserAgent和超时
            request.UserAgent = userAgent;
            request.Timeout = timeout;
            if (Headers != null)
            {//如果整个headers信息传入
                request.Headers = Headers;
            }
            else if (header != null)//如果字典方式传入
            {
                foreach (string key in header.Keys)
                {
                    request.Headers.Add(key + ":" + header[key]);
                }
            }
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            //发送POST数据  
            if (!(paras == null || paras.Count == 0))
            {
                StringBuilder buffer = new StringBuilder();
                int i = 0;
                foreach (string key in paras.Keys)
                {
                    if (i > 0)
                    {
                        buffer.AppendFormat("&{0}={1}", key, paras[key]);
                    }
                    else
                    {
                        buffer.AppendFormat("{0}={1}", key, paras[key]);
                    }
                    i++;
                }
                //UTF8发送
                byte[] data = Encoding.UTF8.GetBytes(buffer.ToString());
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }
            }
            string[] values = request.Headers.GetValues("Content-Type");
            try
            {
                return request.GetResponse() as HttpWebResponse;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }

        /// <summary>
        /// 验证证书
        /// </summary>
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return errors == SslPolicyErrors.None;
        }

    }
}
